using Infrastructure.Attribute;
using Infrastructure.Extensions;
using ZR.Model;
using ZR.Model.Dto;
using ZR.Repository;
using System.Linq;
using ZR.Service.IBusinessService;
using ZR.Model.Dto.Business;
using ZR.Model.Models.ProductionControl;
using ZR.Model.System;
using Infrastructure;
using ZR.Common;
using ZR.Model.Dto.Business.ProductionControl;

namespace ZR.Service.Service
{
    /// <summary>
    /// 订单信息表Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(IOrderPlanService), ServiceLifetime = LifeTime.Transient)]
    public class OrderPlanService : BaseService<OrderPlan>, IOrderPlanService
    {
        /// <summary>
        /// 查询订单信息表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<OrderPlanDto> GetList(OrderPlanQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .Where(predicate.ToExpression())
                .ToPage<OrderPlan, OrderPlanDto>(parm);

            return response;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public OrderPlan GetInfo(int Id)
        {
            var response = Queryable()
                .Where(x => x.Id == Id)
                .First();

            return response;
        }

        /// <summary>
        /// 添加订单信息表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OrderPlan AddOrderInfo(OrderPlan model)
        {
            return Insertable(model).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改订单信息表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateOrderInfo(OrderPlan model)
        {
            return Update(model, true);
        }

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<OrderPlan> QueryExp(OrderPlanQueryDto parm)
        {
            var predicate = Expressionable.Create<OrderPlan>();
            predicate.AndIF(!string.IsNullOrEmpty(parm.OrderCode), a => a.OrderCode.Contains(parm.OrderCode));
            return predicate;
        }

        public (string, object, object) ImportOrderPlans(List<OrderPlan> orders)
        {
            orders.ForEach(x =>
            {
                x.CreationTime = DateTime.Now;
                x.OrderState = 0;
                x.Remark = x.Remark.IsEmpty() ? "数据导入" : x.Remark;
            });
            var x = Context.Storageable(orders)
                .SplitInsert(it => !it.Any())
                .SplitIgnore(it => it.Item.CreatorName == GlobalConstant.AdminRole)
                .SplitError(x => x.Item.OrderCode.IsEmpty(), "订单不能为空")
                //.WhereColumns(it => it.UserName)//如果不是主键可以这样实现（多字段it=>new{it.x1,it.x2}）
                .ToStorage();
            var result = x.AsInsertable.ExecuteCommand();//插入可插入部分;

            string msg = string.Format(" 插入{0} 更新{1} 错误数据{2} 不计算数据{3} 删除数据{4} 总共{5}",
                               x.InsertList.Count,
                               x.UpdateList.Count,
                               x.ErrorList.Count,
                               x.IgnoreList.Count,
                               x.DeleteList.Count,
                               x.TotalList.Count);
            //输出统计
            Console.WriteLine(msg);

            //输出错误信息
            //foreach (var item in x.ErrorList)
            //{
            //    Console.WriteLine("userName为" + item.Item.UserName + " : " + item.StorageMessage);
            //}
            //foreach (var item in x.IgnoreList)
            //{
            //    Console.WriteLine("userName为" + item.Item.UserName + " : " + item.StorageMessage);
            //}

            return (msg, x.ErrorList, x.IgnoreList);
        }

        public PagedInfo<OrderPlan> SelectOrderPlanList(OrderPlanQueryDto user, PagerInfo pager)
        {
            var orders = Queryable();
            return orders.ToPage(pager);
        }

        public string UpdateOrderStateForActivate(int id, int state)
        {
            var orderPlanInfo = QueryByClause(qbc => qbc.Id.Equals(id));
            if (orderPlanInfo == null)
            {
                return "-2";
            }
            //激活订单校验
            if (state == 1)
            {
                var has = QueryByClause(a => a.OrderState.Equals(state));
                if (has != null)
                {
                    return "-1";
                }
            }

            orderPlanInfo.OrderState = state;
            return Update(orderPlanInfo).ToString();
        }
    }
}